﻿using DAL3;
using Model3._5;
using Newtonsoft.Json;
using S7.Net;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace GEMINI_OP10
{
    public partial class FormMain : Form
    {
        public string str = "未连接";
        string strs = "";
        int PLC_Count = 2;
        Socket socketSend;
        Socket socketSendGun;
        public string server = "";
        string[] typeArray = new string[150];
        string[] EMArray = new string[150];
        string[] EMArrayName = new string[150];
        string[] EMArray1 = new string[150];
        string[] EMArray1Name = new string[150];
        string[] EMArray2 = new string[150];
        string[] EMArray2Name = new string[150];
        string[] EMArray3 = new string[150];
        string[] EMArray3Name = new string[150];
        string[] saoma = new string[2];
        public string[] alarmNum = new string[20];     //用于读取报警显示
        public bool clear;          //用于清除报警显示
        string icID;
        string result;
        int num1;
        //int num3; 
        int model;          //用于记录当前型号，方便扫码时快速比较。 //model表示各个型号，1:DIDI、2:百度前空调、3:百度后空调
        public struct proData
        {
            public static string typeName;
            public static string Ewm;
            public static string testStation;
            public static string allResult;
            public static double positivePressureValue;
            public static double negativePressureValue;
            public static string operatorter;
            public static string serialNumber;
            public static bool save;
        }
        public struct plcStructIn
        {
            //DB块中依次8个bool量
            public bool bool_0;
            public bool bool_1;
            public bool bool_2;
            public bool bool_3;
            public bool bool_4;
            public bool bool_5;
            public bool bool_6;
            public bool bool_7;
            //DB块中依次6个byte量
            public byte byte_0;
            public byte byte_1;
            public byte byte_2;//生产型号
            public byte byte_3;
            public byte byte_4;
            public byte byte_5;
            //DB块中依次8个int量
            public Int16 int_0;
            public Int16 int_1;
            public Int16 int_2;
            public Int16 int_3;
            public Int16 int_4;
            public Int16 int_5;
            public Int16 int_6;
            public Int16 int_7;

            //public UInt32 Uint_0;//序列号

        }
        //----线程循环
        bool _Continue = true;
        //----PLC监控线程数组
        Thread[] PLC_Td;
        //PLC实例数组
        public static SimenesPLC[] PLC_Link;
        //PLC DB结构数组
        public plcStructIn[] Struct_Test;
        public static plcStructIn _plcStruct = new plcStructIn();
        private string ID;
        public static FormMain FM10;
        public FormMain()
        {
            InitializeComponent();
            FM10 = (FormMain)this;
        }
        /// <summary>
        /// 打开窗体,将页面嵌入到主窗体
        /// </summary>
        /// <param name="form"></param>
        private void OpenForm(Form form)
        {
            //将当前子窗体设置成非顶级控件
            form.TopLevel = false;
            //设置窗体最大化
            form.WindowState = FormWindowState.Maximized;
            //设置窗体无边框
            form.FormBorderStyle = FormBorderStyle.None;
            //设置窗体嵌入容器
            form.Parent = this.panel1;
            form.Show();
        }
        /// <summary>
        /// 关闭窗体,将容器内窗体移除
        /// </summary>
        private void CloseForm()
        {
            //遍历这个容器里面的所有控件,找出窗体对象
            foreach (Control item in this.panel1.Controls)
            {
                if (item is Form)
                {
                    Form form = (Form)item;
                    form.Close();
                    //移除
                    this.panel1.Controls.Remove(item);
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }
        //用户登录按钮
        private void button1_Click(object sender, EventArgs e)
        {
            //嵌入窗口
            //this.CloseForm();
            FormUserLoginInterface formUserLoginInterface = new FormUserLoginInterface();
            //this.OpenForm(formUserLoginInterface);
            formUserLoginInterface.Show();
        }

        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //PLC_Link[1].plc.WriteBit(DataType.DataBlock, 99, 146, 4, 0);
            //关闭主窗体时释放后台线程的资源
            for (int I = 0; I < PLC_Count; I++)
            {
                if (PLC_Td[I] != null)
                {
                    PLC_Td[I].Abort();
                }
            }
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            //取消跨线程的访问
            Control.CheckForIllegalCrossThreadCalls = false;
            #region 向服务器获取所有产品型号和扫码设置
            string sql = "select [typeName], [OP10扫码1名称], [OP10扫码1], [OP10扫码2名称], [OP10扫码2], [OP10扫码3名称], [OP10扫码3], [OP10扫码4名称], [OP10扫码4] from parameterSetting";
            SqlDataReader objReader = SQLHelp.GetReader(sql);
            int temp2 = 0;
            while (objReader.Read())
            {
                EMArray[temp2] = objReader["OP10扫码1"].ToString();
                EMArrayName[temp2] = objReader["OP10扫码1名称"].ToString();
                EMArray1[temp2] = objReader["OP10扫码2"].ToString();
                EMArray1Name[temp2] = objReader["OP10扫码2名称"].ToString();
                EMArray2[temp2] = objReader["OP10扫码3"].ToString();
                EMArray2Name[temp2] = objReader["OP10扫码3名称"].ToString();
                EMArray3[temp2] = objReader["OP10扫码4"].ToString();
                EMArray3Name[temp2] = objReader["OP10扫码4名称"].ToString();
                typeArray[temp2] = objReader["typeName"].ToString();
                comboBox1.Items.Add(typeArray[temp2]);
                comboBox3.Items.Add(typeArray[temp2]);
                comboBox2.Items.Add(EMArray[temp2]);
                comboBox2.Items.Add(EMArray1[temp2]);
                comboBox2.Items.Add(EMArray2[temp2]);
                comboBox2.Items.Add(EMArray3[temp2]);
                temp2 += 1;
            }
            objReader.Close();
            #endregion
            #region 连接PLC
            PLC_Td = new Thread[PLC_Count];
            PLC_Link = new SimenesPLC[PLC_Count];
            Struct_Test = new plcStructIn[PLC_Count];
            for (int I = 0; I < PLC_Count; I++)
            {
                PLC_Td[I] = new Thread(PLC_Td_Func);
                PLC_Td[I].IsBackground = true;
                PLC_Td[I].Start(I);
            }
            #endregion

            #region 与服务器tcp/ip通讯建立连接
            try
            {
                //创建负责通信的Socket
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse("172.16.150.1");
                IPEndPoint point = new IPEndPoint(ip, 50001);
                //获得要连接的远程服务器应用程序的IP地址和端口号
                socketSend.Connect(point);
                server = "成功";
                //开启一个新的线程不停的接收服务端发来的消息
                Thread th = new Thread(Recive);
                th.IsBackground = true;
                th.Start();
            }
            catch
            {
                server = "失败";
            }

            //Thread thGun = new Thread(gunConnectStart);
            //thGun.IsBackground = true;
            //thGun.Start();

            #endregion

            timer.Enabled = true;
            timer.Interval = 1000;
            timer.AutoReset = false;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);

            timercall.Enabled = true;
            timercall.Interval = 1000;
            timercall.AutoReset = false;
            timercall.Elapsed += new System.Timers.ElapsedEventHandler(timercall_Elapsed);

            #region 设置串口参数并打开串口接收
            //波特率

            //IC卡
            //serialPort1.BaudRate = 9600;
            //扫码
            serialPort2.BaudRate = 115200;

            //数据位

            //IC卡
            //serialPort1.DataBits = 8;
            //扫码
            serialPort2.DataBits = 8;

            //奇偶校验位
            //serialPort1.Parity = System.IO.Ports.Parity.None;
            serialPort2.Parity = System.IO.Ports.Parity.None;

            //停止位
            //serialPort1.StopBits = System.IO.Ports.StopBits.One;
            serialPort2.StopBits = System.IO.Ports.StopBits.One;

            string[] contents = new string[5];
            try
            {
                contents = File.ReadAllLines(Application.StartupPath + "\\COM口配置.txt", Encoding.UTF8);
            }
            catch
            {
                label28.Text += "请检查COM口配置文件！";
            }
            //端口
            //try
            //{
            //    serialPort1.PortName = contents[0];
            //    serialPort1.DataReceived += new SerialDataReceivedEventHandler(SerialPort1_DataReceived);
            //    serialPort1.Open();

            //}
            //catch
            //{
            //    MessageBox.Show("IC卡端口打开失败,请检查串口连接是否正确！", "错误提示");
            //}

            try
            {
                serialPort2.PortName = contents[1];
                serialPort2.DataReceived += new SerialDataReceivedEventHandler(SerialPort2_DataReceived);
                serialPort2.Open();
            }
            catch
            {
                MessageBox.Show("扫码端口打开失败,请检查串口连接是否正确！", "错误提示");
            }
            #endregion
            //Thread guning = new Thread(dading);
            //guning.IsBackground = true;
            //guning.Start();

        }
        //PLC线程
        int[] screwRecordingCompleted = new int[21];
        bool TStart;
        bool Tdading;
        private void PLC_Td_Func(object ob)
        {
            Ping p = new Ping();
            int num = (int)ob;
            string[] PLC_IP = new string[PLC_Count];
            PLC_IP[1] = "172.16.1.2";
            PLC_Link[1] = new SimenesPLC(CpuType.S71500, PLC_IP[1].ToString(), 0, 1);

            while (_Continue)
            {
                try
                {
                    //处理相应的PLC对象的数据处理
                    if (p.Send(PLC_IP[1], 200).Status == IPStatus.Success)//如果200ms时间间隔ping通了
                    {
                        if (PLC_Link[1].plc.IsConnected == false)//plc没有连接上
                        {
                            //int s = (int)PLC_Link[1].plc.Open();
                            //strs = Convert.ToString(s);
                            //if (s == 0)
                            //{
                            //    str = "成功";
                            //    SimenesPLC.conectStatus = true;
                            //}
                            //else
                            //{
                            //    str = "失败";
                            //    SimenesPLC.conectStatus = false;
                            //}
                            lock (this)
                            {
                                try
                                {
                                    PLC_Link[1].plc.Open();
                                    SimenesPLC.conectStatus = true;
                                    str = "成功";
                                }
                                catch (Exception)
                                {
                                    SimenesPLC.conectStatus = false;
                                    str = "失败";
                                    throw;
                                }
                            }
                        }
                        else
                        {
                            str = "成功";
                            //读取DB
                            try
                            {
                                Struct_Test[1] = (plcStructIn)PLC_Link[1].plc.ReadStruct(typeof(plcStructIn), 99, 280);
                                _plcStruct = Struct_Test[1];    //_plcStruct为地址DB99.280开始
                                ID = PLC_Link[1].plc.Read(DataType.DataBlock, 99, 156, VarType.DInt, 1).ToString();
                            }
                            catch (Exception)
                            {
                                //throw;
                            }
                            label45.Text = _plcStruct.byte_2.ToString();
                            try
                            {
                                if ((Byte)PLC_Link[1].plc.Read(DataType.DataBlock, 99, 2, VarType.Byte, 1) > 0 && (Byte)PLC_Link[1].plc.Read(DataType.DataBlock, 99, 2, VarType.Byte, 1) < 150)
                                {
                                    #region 向服务器获取所有产品型号和扫码设置
                                    label28.Text = "向服务器获取所有产品型号和扫码设置";
                                    string sql = "select [typeName],[OP10扫码1名称], [OP10扫码1], [OP10扫码2名称], [OP10扫码2], [OP10扫码3名称], [OP10扫码3], [OP10扫码4名称], [OP10扫码4] from parameterSetting";
                                    SqlDataReader objReader = SQLHelp.GetReader(sql);
                                    int temp2 = 0;
                                    while (objReader.Read())
                                    {
                                        if (temp2 == 0)
                                        {
                                            comboBox1.Items.Clear();
                                            comboBox2.Items.Clear();
                                        }
                                        EMArray[temp2] = objReader["OP10扫码1"].ToString();
                                        EMArrayName[temp2] = objReader["OP10扫码1名称"].ToString();
                                        EMArray1[temp2] = objReader["OP10扫码2"].ToString();
                                        EMArray1Name[temp2] = objReader["OP10扫码2名称"].ToString();
                                        EMArray2[temp2] = objReader["OP10扫码3"].ToString();
                                        EMArray2Name[temp2] = objReader["OP10扫码3名称"].ToString();
                                        EMArray3[temp2] = objReader["OP10扫码4"].ToString();
                                        EMArray3Name[temp2] = objReader["OP10扫码4名称"].ToString();
                                        typeArray[temp2] = objReader["typeName"].ToString();
                                        comboBox1.Items.Add(typeArray[temp2]);
                                        comboBox2.Items.Add(EMArray[temp2]);
                                        comboBox2.Items.Add(EMArray1[temp2]);
                                        comboBox2.Items.Add(EMArray2[temp2]);
                                        comboBox2.Items.Add(EMArray3[temp2]);
                                        temp2 += 1;
                                    }
                                    objReader.Close();
                                    #endregion
                                }
                            }
                            catch (Exception)
                            {

                                //throw;
                            }

                            if (_plcStruct.byte_2 > 0 && _plcStruct.byte_2 != tmptyp && _plcStruct.byte_2 < 150)
                            {
                                try
                                {
                                    tmptyp = _plcStruct.byte_2;
                                    if (EMArray[_plcStruct.byte_2 - 1].Equals("0"))
                                    {
                                        label20.Visible = false;
                                        label21.Visible = false;
                                        label20.Text = "";
                                        label21.Text = "";
                                    }
                                    else
                                    {
                                        label20.Visible = true;
                                        label21.Visible = true;
                                        label21.Text = EMArrayName[_plcStruct.byte_2 - 1];
                                    }

                                    if (EMArray1[_plcStruct.byte_2 - 1].Equals("0"))
                                    {
                                        label29.Visible = false;
                                        label30.Visible = false;
                                        label29.Text = "";
                                        label30.Text = "";
                                    }
                                    else
                                    {
                                        label29.Visible = true;
                                        label30.Visible = true;
                                        label30.Text = EMArray1Name[_plcStruct.byte_2 - 1];
                                    }

                                    if (EMArray2[_plcStruct.byte_2 - 1].Equals("0"))
                                    {
                                        label31.Visible = false;
                                        label32.Visible = false;
                                        label31.Text = "";
                                        label32.Text = "";
                                    }
                                    else
                                    {
                                        label31.Visible = true;
                                        label32.Visible = true;
                                        label32.Text = EMArray2Name[_plcStruct.byte_2 - 1];
                                    }

                                    if (EMArray3[_plcStruct.byte_2 - 1].Equals("0"))
                                    {
                                        label33.Visible = false;
                                        label34.Visible = false;
                                        label33.Text = "";
                                        label34.Text = "";
                                    }
                                    else
                                    {
                                        label33.Visible = true;
                                        label34.Visible = true;
                                        label34.Text = EMArray3Name[_plcStruct.byte_2 - 1];
                                    }
                                    //螺钉1
                                    if (label46.Text == "0")        //螺钉数1为0时，隐藏对应显示框
                                    {
                                        label41.Visible = false;
                                        label42.Visible = false;
                                        label43.Visible = false;
                                        label46.Visible = false;
                                        label47.Visible = false;
                                    }
                                    else
                                    {
                                        label41.Visible = true;
                                        label42.Visible = true;
                                        label43.Visible = true;
                                        label46.Visible = true;
                                        label47.Visible = true;
                                    }
                                    //螺钉2
                                    if (label46.Text == "0")        ////螺钉数2为0时，隐藏对应显示框
                                    {
                                        label44.Visible = false;
                                        label48.Visible = false;
                                        label49.Visible = false;
                                    }
                                    else
                                    {
                                        label44.Visible = true;
                                        label48.Visible = true;
                                        label49.Visible = true;
                                    }
                                }
                                catch (Exception)
                                {

                                    //throw;
                                }

                            }
                            else
                            { }

                            //型号
                            if (_plcStruct.byte_2 > 0 && _plcStruct.byte_2 < 150)
                            {
                                label2.Text = typeArray[_plcStruct.byte_2 - 1];
                                temptype = _plcStruct.byte_2;   //生产型号

                            }
                            //托盘号
                            label5.Text = _plcStruct.byte_3.ToString();
                            //测试时间
                            label7.Text = _plcStruct.int_5 / 60 + "分" + _plcStruct.int_5 % 60 + "秒";
                            //计划生产数
                            label9.Text = _plcStruct.int_0.ToString();
                            //当前生产数
                            label11.Text = _plcStruct.int_1.ToString();
                            //合格数
                            label13.Text = _plcStruct.int_2.ToString();
                            //不合格数
                            label15.Text = _plcStruct.int_3.ToString();
                            ////复测数
                            //label17.Text = _plcStruct.int_4.ToString();
                            //自动模式状态
                            //if (PLC_Link[1].readBoolen("DB1050.DBX24.0"))
                            //{
                            //    button12.BackColor = Color.Green;
                            //}
                            //else
                            //{
                            //    button12.BackColor = Color.Silver;
                            //}
                            //手动模式状态
                            //if (PLC_Link[1].readBoolen("DB1050.DBX24.1"))
                            //{
                            //    button11.BackColor = Color.Green;
                            //}
                            //else
                            //{
                            //    button11.BackColor = Color.Silver;
                            //}
                            //呼叫系统
                            try
                            {
                                if (Convert.ToBoolean(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 616, VarType.Bit, 1, 0)))
                                {
                                    button7.BackColor = Color.Green;
                                }
                                else
                                {
                                    button7.BackColor = Color.Aquamarine;
                                }
                                if (Convert.ToBoolean(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 616, VarType.Bit, 1, 1)))
                                {
                                    button8.BackColor = Color.Green;
                                }
                                else
                                {
                                    button8.BackColor = Color.Aquamarine;
                                }
                            }
                            catch (Exception)
                            {

                                //throw;
                            }
                            try
                            {
                                ////查看拍照
                                //if ((bool)PLC_Link[1].plc.Read(DataType.DataBlock, 99, 280, VarType.Bit, 1, 0) && TStart == false)
                                //{
                                //    //timerPhoto.Enabled = true;
                                //    //timerPhoto.Interval = 1000;
                                //    //timerPhoto.AutoReset = false;
                                //    //timerPhoto.Elapsed += new System.Timers.ElapsedEventHandler(timerPhoto_Elapsed);
                                //    //List<Label> lab = new List<Label> { useTable1, useTable2, useTable3, useTable4, useTable5, useTable6, useTable7, useTable8, useTable9, useTable10, useTable11, useTable12, useTable13, useTable14, useTable15, useTable16, useTable17, useTable18, useTable19 };
                                //    //for (int i = 0; i < 10; i++)
                                //    //{
                                //    //    lab[i].Visible = false;
                                //    //}
                                //    //timerPhoto.Start();
                                //    //TStart = true;
                                //    //Tdading = false;
                                //    //button5.BackColor = Color.Green;
                                //    //button6.BackColor = Color.Aqua;
                                //}
                                ////查看打钉
                                //else if ((bool)PLC_Link[1].plc.Read(DataType.DataBlock, 99, 280, VarType.Bit, 1, 1) && Tdading == false)
                                //{
                                //    for (int i = 0; i < 3; i++)
                                //    {
                                //        timerPhoto.Stop();
                                //        Thread.Sleep(10);
                                //    }
                                //    dading();
                                //    Tdading = true;
                                //    TStart = false;
                                //    button5.BackColor = Color.Aqua;
                                //    button6.BackColor = Color.Green;
                                //}
                            }
                            catch (Exception)
                            {

                                //throw;
                            }
                            //打钉更新
                            try
                            {
                                if (_plcStruct.byte_0 + _plcStruct.byte_1 > 0)
                                {
                                    List<Label> lab = new List<Label> { useTable1, useTable2, useTable3, useTable4, useTable5, useTable6, useTable7, useTable8, useTable9, useTable10, useTable11, useTable12, useTable13, useTable14, useTable15, useTable16, useTable17, useTable18, useTable19 };
                                    for (int i = 0; i < _plcStruct.byte_0 + _plcStruct.byte_1; i++)
                                    {
                                        lab[i].BackColor = Color.Green;
                                    }
                                }
                                else if (_plcStruct.byte_0 + _plcStruct.byte_1 == 0)
                                {
                                    List<Label> lab = new List<Label> { useTable1, useTable2, useTable3, useTable4, useTable5, useTable6, useTable7, useTable8, useTable9, useTable10, useTable11, useTable12, useTable13, useTable14, useTable15, useTable16, useTable17, useTable18, useTable19 };
                                    for (int i = 0; i < _plcStruct.byte_0 + _plcStruct.byte_1; i++)
                                    {
                                        lab[i].BackColor = Color.Yellow;
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                //throw;
                            }
                            //步骤提示
                            try
                            {
                                stepNum = File.ReadAllLines(Application.StartupPath + "\\步骤配置.txt", Encoding.UTF8);
                                label51.Text = stepNum[PLC_Link[1].readInt("DB1050.DBW90.0")];
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                            //打钉
                            try
                            {
                                //螺钉1设置数
                                label46.Text = PLC_Link[1].ReadByte(DataType.DataBlock, 99, 696).ToString();
                                //螺钉1完成数
                                label47.Text = PLC_Link[1].ReadByte(DataType.DataBlock, 99, 674).ToString();
                                //螺钉2设置数
                                label48.Text = PLC_Link[1].ReadByte(DataType.DataBlock, 99, 697).ToString();
                                //螺钉2完成数
                                label49.Text = PLC_Link[1].ReadByte(DataType.DataBlock, 99, 675).ToString();
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                            if (_plcStruct.bool_5)
                            {
                                result = "合格";
                                label26.Text = "合格";
                                label26.BackColor = System.Drawing.Color.Green;
                            }
                            else if (_plcStruct.bool_6)
                            {
                                result = "不合格";
                                label26.Text = "不合格";
                                label26.BackColor = System.Drawing.Color.Red;
                            }
                            else
                            {
                                result = "未完成";
                                label26.Text = "未完成";
                                label26.BackColor = System.Drawing.Color.Silver;

                                if (proData.save == true || PLC_Link[1].readBoolen("DB1050.DBX1.1"))        //该工件完成或者读取到返回原位信号，进行初始化清除操作。
                                {
                                    PLC_Link[1].plc.WriteBit(DataType.DataBlock, 99, 146, 0, 0);    //扫码OK清0
                                    PLC_Link[1].plc.WriteBit(DataType.DataBlock, 99, 146, 1, 0);    //扫码NG清0
                                    PLC_Link[1].plc.WriteBit(DataType.DataBlock, 99, 146, 2, 0);    //数据传输完成清0
                                    label20.Text = "";
                                    label20.BackColor = System.Drawing.Color.Silver;
                                    label29.Text = "";
                                    label29.BackColor = System.Drawing.Color.Silver;
                                    label31.Text = "";
                                    label31.BackColor = System.Drawing.Color.Silver;
                                    label33.Text = "";
                                    label33.BackColor = System.Drawing.Color.Silver;
                                    tempEM1ok = false;
                                    tempEM2ok = false;
                                    tempEM3ok = false;
                                    tempEM4ok = false;
                                    label242.Text = "";
                                    label28.Text = "复位完成";

                                    try
                                    {
                                        //CopyAllFile(@"d:\1", @"D:\照片\" + label37.Text);

                                        //deletePhtor(@"d:\1", ".jpeg");
                                    }
                                    catch (Exception)
                                    {
                                        //throw;
                                    }
                                    List<Label> lab = new List<Label> { useTable1, useTable2, useTable3, useTable4, useTable5, useTable6, useTable7, useTable8, useTable9, useTable10, useTable11, useTable12, useTable13, useTable14, useTable15, useTable16, useTable17, useTable18, useTable19 };
                                    for (int i = 0; i < 19; i++)
                                    {
                                        lab[i].BackColor = Color.Yellow;
                                    }
                                    label37.Text = "";
                                    label37.BackColor = System.Drawing.Color.Silver;
                                    for (int i = 0; i < 21; i++)
                                    {
                                        screwRecordingCompleted[i] = 0;
                                    }
                                    if (_plcStruct.bool_7 == false && screwRecordingCompleted[20] != 0)
                                    {
                                        screwRecordingCompleted[20] = 0;
                                        TStart = false;
                                        Tdading = false;
                                    }
                                }

                                proData.save = false;
                            }

                            //创建数据记录
                            proData.operatorter = Program.userlogin.Admin;//操作员
                            label39.Text = Program.userlogin.Admin;
                            label40.Text = Program.userlogin.serialNumber.ToString();

                            #region 创建数据
                            //if (screwRecordingCompleted[20] == 0 && _plcStruct.bool_7 && !ID.Equals(tmpid))
                            //{
                            //    tmpid = ID;
                            //    FileStream fs = new FileStream("日志.txt", FileMode.Append);
                            //    StreamWriter sw = new StreamWriter(fs);
                            //    label28.Text = "创建数据";
                            //    sw.WriteLine(System.DateTime.Now + "-" + ID + "-" + "创建数据");
                            //    string sql = "insert into productData([产品型号],[OP10操作员],[ID],[托盘号]) values('{0}','{1}','{2}','{3}')";
                            //    sql = string.Format(sql, label2.Text, proData.operatorter, ID, label5.Text);
                            //    try
                            //    {
                            //        screwRecordingCompleted[20] = SQLHelp.AddData(sql);
                            //        if (screwRecordingCompleted[20] > 0)
                            //        {
                            //            PLC_Link[1].plc.WriteBit(DataType.DataBlock, 99, 146, 2, 1);
                            //            label28.Text = "创建成功";
                            //            sw.WriteLine(System.DateTime.Now + "-" + ID + "-" + "创建完成");
                            //        }
                            //        sw.Close();
                            //        fs.Close();
                            //    }
                            //    catch (Exception e)
                            //    {
                            //        label28.Text = "创建失败";
                            //        sw.WriteLine(System.DateTime.Now + "-" + ID + "-" + "创建失败" + e.ToString());
                            //        sw.Close();
                            //        fs.Close();
                            //        //throw;
                            //    }
                            //} 
                            #endregion
                            //登录权限给PLC
                            if (Program.userlogin.Admin != "")
                            {
                                var flag = PLC_Link[1].plc.IsConnected;
                                if (!flag) PLC_Link[1].connectPLC();
                                PLC_Link[1].plc.WriteBit(DataType.DataBlock, 99, 146, 4, 1);
                            }
                            else
                            {
                                PLC_Link[1].plc.WriteBit(DataType.DataBlock, 99, 146, 4, 0);
                            }
                            //更新数据记录
                            if (_plcStruct.bool_4 && proData.save == false) //DB99.280.4 OP10过程完成信号
                            {
                                try
                                {
                                    FileStream fs = new FileStream("日志.txt", FileMode.Append);
                                    StreamWriter sw = new StreamWriter(fs);
                                    label28.Text = "开始记录数据";
                                    sw.WriteLine(System.DateTime.Now + "-" + ID + "-" + "开始记录数据");
                                    //历史记录                                                           //_plcStruct -DB99.280  // _plcStruct.byte_0, _plcStruct.byte_1
                                    string sql = "update productData set [OP10结果] ='{0}'/*,[内部码]='{1}'*/,[OP10操作时间]='{2}',[OP10螺钉数1]='{3}',[OP10螺钉数2]='{4}',[托盘号]='{5}',[产品型号]='{6}',[返修次数]='{7}' where ID = '{8}'";     //未完成  230524增加了返修次数填0
                                    sql = string.Format(sql, result, label37.Text, label7.Text, _plcStruct.byte_0, _plcStruct.byte_1, label5.Text, label2.Text, 0, ID);
                                    //23/6/9取消OP10新建电检数据    待验证
                                    //string sql2 = "insert into productDataToDJ([ID],[内部码],[产品型号]) values('{0}','{1}','{2}')";
                                    //sql2 = string.Format(sql2, ID, label37.Text, label2.Text);
                                    try
                                    {
                                        //num3 = SQLHelp.AddData(sql2);
                                        num1 = SQLHelp.AddData(sql);
                                        if ((num1 > 0) /*&& (num3 > 0)*/)
                                        {
                                            label28.Text = label37.Text;
                                            sw.WriteLine(System.DateTime.Now + "-" + ID + "-" + "总结果" + result);
                                            sw.WriteLine(System.DateTime.Now + "-" + ID + "-" + "内部码" + label37.Text);
                                            sw.WriteLine(System.DateTime.Now + "-" + ID + "-" + "记录完成");
                                        }
                                        else
                                        {
                                            sw.WriteLine(System.DateTime.Now + "-" + ID + "-" + "记录未添加进数据库,受影响行数为0");
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        MessageBox.Show(Convert.ToString(e), "错误提示!");
                                        sw.WriteLine(System.DateTime.Now + "-" + ID + "-" + "记录异常" + Convert.ToString(e));
                                        sw.Close();
                                        fs.Close();
                                    }
                                    //if ((bool)PLC_Link[1].plc.Read(DataType.DataBlock, 99, 280, VarType.Bit, 1, 2))
                                    //{
                                    //    label37.Text = label37.Text + "返";
                                    //}
                                    //string sql1 = "insert into tiaoma([内部码],[ID],[OP10扫码1],[OP10扫码2],[OP10扫码3],[OP10扫码4],[OP10扫码1名称],[OP10扫码2名称],[OP10扫码3名称],[OP10扫码4名称]) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')";
                                    //string sql1 = "update productData set [内部码] ='{0}' where ID = '{1}'";  //,[OP10扫码1] ='{0}',[OP10扫码2]='{1}',[OP10扫码3]='{2}',[OP10扫码4]='{3}',[OP10扫码1名称]='{4}' ,[OP10扫码2名称]='{5}',[OP10扫码3名称]='{6}',[OP10扫码4名称]='{7}'
                                    //OP10以下两行未验证
                                    string sql1 = "update tiaoma set[OP10扫码1]='{0}',[OP10扫码2]= '{1}',[OP10扫码3]='{2}',[OP10扫码4]='{3}',[OP10扫码1名称]='{4}',[OP10扫码2名称]='{5}',[OP10扫码3名称]='{6}',[OP10扫码4名称]='{7}' where [ID] = '{8}'";
                                    sql1 = string.Format(sql1,label20.Text, label29.Text, label31.Text, label33.Text,/*label37.Text,*/ label21.Text, label30.Text, label32.Text, label34.Text, ID);   // label20.Text, label29.Text, label31.Text, label33.Text, label21.Text, label30.Text, label32.Text, label34.Text,
                                    try
                                    {
                                        num2 = SQLHelp.AddData(sql1);
                                    }
                                    catch (Exception e)
                                    {
                                        label28.Text = Convert.ToString(e);
                                        sw.WriteLine(System.DateTime.Now + "-" + ID + "-" + "记录失败" + e.ToString());
                                        sw.Close();
                                        fs.Close();
                                    }

                                    sw.Close();
                                    fs.Close();
                                    //给PLC发送记录完成信号
                                    if (num1 == 1 && num2 == 1 /*&& num3 == 1*/)
                                    {
                                        label28.Text = "数据记录完成";
                                        PLC_Link[1].plc.WriteBit(DataType.DataBlock, 99, 146, 2, 1);
                                    }
                                    //screwRecordingCompleted[20] = 0;
                                }
                                catch (Exception)
                                {

                                    // throw;
                                }
                                proData.save = true;
                            }
                        }
                    }
                    else
                    {
                        //PLC_Link[1].plc.Close();
                        str = "ping失败";
                    }
                    if (p.Send("172.16.150.1", 200).Status == IPStatus.Success)
                    {
                        server = "成功";
                    }
                    else
                    {
                        server = "ping失败";
                    }
                }
                catch (Exception ex1)
                {
                    //str = "出现异常";
                    //MessageBox.Show(Convert.ToString(ex1), "错误提示!");

                }

                if (str.Equals("成功"))
                {
                    label23.BackColor = System.Drawing.Color.Green;
                }
                else
                {
                    label23.BackColor = System.Drawing.Color.Red;
                }
                if (server.Equals("成功"))
                {
                    label22.BackColor = System.Drawing.Color.Green;
                }
                else
                {
                    label22.BackColor = System.Drawing.Color.Red;
                }
                Thread.Sleep(100);
                label18.Text = DateTime.Now.ToString("yyyy/MM/dd");
                label19.Text = DateTime.Now.ToLongTimeString();
                if (label242.Text == "")
                {
                    label242.Text = "使用公司：空调国际(上海)有限公司   \t 设备公司：重庆英之拓智能设备有限公司  \t  软件版本号：V2.0";
                    label242.Text = string.Format(label242.Text, Program.userlogin.name);
                }
                else
                {

                }
            }

        }

        /// <summary>
        /// 不停的接受服务器发来的消息
        /// </summary>
        void Recive()
        {
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024];
                    int r = socketSend.Receive(buffer);
                    //实际接收到的有效字节数
                    if (r == 0)
                    {
                        break;
                    }
                    //表示发送的字符消息,并且是所有产品型号
                    if (buffer[0] == 0)
                    {
                        string s = Encoding.UTF8.GetString(buffer, 1, r - 1);

                        //0 5 ,aaa,asas,dsds,gfhh,hhggh,
                        //截取所有型号
                        typeArray = s.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    }
                    //表示发送的字符消息,并且是扫码参数
                    if (buffer[0] == 1)
                    {
                        string s = Encoding.UTF8.GetString(buffer, 1, r - 1);
                        //1,hhggh
                        //截取扫码参数设置
                        saoma = s.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    }
                    //else if (buffer[0] == 1)
                    //{
                    //    SaveFileDialog sfd = new SaveFileDialog();
                    //    sfd.InitialDirectory = @"C:\Users\SpringRain\Desktop";
                    //    sfd.Title = "请选择要保存的文件";
                    //    sfd.Filter = "所有文件|*.*";
                    //    sfd.ShowDialog(this);
                    //    string path = sfd.FileName;
                    //    using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                    //    {
                    //        fsWrite.Write(buffer, 1, r - 1);
                    //    }
                    //    MessageBox.Show("保存成功");
                    //}
                    //else if (buffer[0] == 2)
                    //{
                    //    ZD();
                    //}

                }
                catch { }
                Thread.Sleep(1000);

            }
        }
        void ReciveGan()
        {
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[10240];
                    int r = socketSendGun.Receive(buffer);
                    //实际接收到的有效字节数
                    if (r == 0)
                    {
                        break;
                    }
                    if (buffer != null)
                    {
                        string str1 = "";
                        for (int i = 0; i < buffer.Length; i++)
                        {
                            //为C#中的字符串格式控制符
                            str1 += buffer[i].ToString("X2");//ToString("X2")
                        }
                        //textBox1.Text = stringHextoASCII(str1);
                        string temps = stringHextoASCII(str1);
                        //textBox1.Text = temps.Substring(temps.IndexOf("30237"),29);
                        string tempa = "";
                        if (Convert.ToInt32(temps.Substring(temps.IndexOf("30237"), 29).Substring(26)) > 0)
                        {
                            tempa = (temps.Substring(temps.IndexOf("30237"), 29).Substring(16, 5)) + temps.Substring(temps.IndexOf("30237"), 29).Substring(22, Convert.ToInt32(temps.Substring(temps.IndexOf("30237"), 29).Substring(27))) + "." + (Convert.ToInt32(temps.Substring(temps.IndexOf("30237"), 29).Substring(27)) < 3 ? temps.Substring(temps.IndexOf("30237"), 29).Substring(22 + Convert.ToInt32(temps.Substring(temps.IndexOf("30237"), 29).Substring(28)), 3 - Convert.ToInt32(temps.Substring(temps.IndexOf("30237"), 29).Substring(28))) : "");
                        }
                        else
                        {
                            tempa = (temps.Substring(temps.IndexOf("30237"), 29).Substring(16, 5 - Convert.ToInt32(temps.Substring(temps.IndexOf("30237"), 29).Substring(27)))) + "." + temps.Substring(temps.IndexOf("30237"), 29).Substring(21 - Convert.ToInt32(temps.Substring(temps.IndexOf("30237"), 29).Substring(27)), Convert.ToInt32(temps.Substring(temps.IndexOf("30237"), 29).Substring(27))) + temps.Substring(temps.IndexOf("30237"), 29).Substring(22, 3);
                        }
                        //label41.Text = tempa;
                        //textBox1.Text += temps.Substring(temps.IndexOf("30238"), 29);
                        string tempb = "";
                        if (Convert.ToInt32(temps.Substring(temps.IndexOf("30238"), 29).Substring(26)) > 0)
                        {
                            tempb = (temps.Substring(temps.IndexOf("30238"), 29).Substring(16, 5)) + temps.Substring(temps.IndexOf("30238"), 29).Substring(22, Convert.ToInt32(temps.Substring(temps.IndexOf("30238"), 29).Substring(27))) + "." + (Convert.ToInt32(temps.Substring(temps.IndexOf("30238"), 29).Substring(27)) < 3 ? temps.Substring(temps.IndexOf("30238"), 29).Substring(22 + Convert.ToInt32(temps.Substring(temps.IndexOf("30238"), 29).Substring(28)), 3 - Convert.ToInt32(temps.Substring(temps.IndexOf("30238"), 29).Substring(28))) : "");
                        }
                        else
                        {
                            tempb = (temps.Substring(temps.IndexOf("30238"), 29).Substring(16, 5 - Convert.ToInt32(temps.Substring(temps.IndexOf("30238"), 29).Substring(27)))) + "." + temps.Substring(temps.IndexOf("30238"), 29).Substring(21 - Convert.ToInt32(temps.Substring(temps.IndexOf("30238"), 29).Substring(27)), Convert.ToInt32(temps.Substring(temps.IndexOf("30238"), 29).Substring(27))) + temps.Substring(temps.IndexOf("30238"), 29).Substring(22, 3);
                        }
                        //label42.Text = tempb;
                    }

                }
                catch { }

            }
        }
        //IC卡

        private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {

                Thread.Sleep(50);
                byte[] byteRead1 = new byte[serialPort1.BytesToRead];
                serialPort1.Read(byteRead1, 0, byteRead1.Length);
                byte[] temp6 = new byte[1];
                temp6[0] = byteRead1[20];
                icID = byteToHexStr(temp6, 1);
                Program.userlogin = UserManagement.GetUser(Convert.ToInt32(icID));
                //label242.Text = "当前登录用户：{0} \t\t  使用公司：空调国际(上海)有限公司   \t 设备公司：重庆英之拓智能设备有限公司  \t  软件版本号：V1.0";
                //label242.Text = string.Format(label242.Text, Program.userlogin.name);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc + "接收失败");
            }

        }
        //扫码枪
        bool tempEM1ok;
        bool tempEM2ok;
        bool tempEM3ok;
        bool tempEM4ok;
        private void SerialPort2_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                Thread.Sleep(100);
                byte[] byteRead = new byte[serialPort2.BytesToRead];
                serialPort2.Read(byteRead, 0, byteRead.Length);
                string indata = Encoding.UTF8.GetString(byteRead);
                label52.Text = indata;
                if ((indata.Contains("D01") && model == 1) || (indata.Contains("BF") && model == 2) || (indata.Contains("BR") && model == 3))      //model表示各个型号，1:DIDI、2:百度前空调、3:百度后空调
                {
                    label37.Text = indata;
                    label37.BackColor = Color.Green;
                    #region 查询ID
                    string sql = "select [ID] from productData where [内部码] = '" + label37.Text + "'";
                    SqlDataReader objReader = SQLHelp.GetReader(sql);
                    int temp2 = 0;
                    while (objReader.Read())
                    {
                        temp2 = 1;
                        PLC_Link[1].plc.Write("DB99.DBD156", Convert.ToUInt32(objReader["ID"]));
                        label28.Text = objReader["ID"].ToString();
                    }
                    objReader.Close();
                    #endregion
                    if ((bool)PLC_Link[1].plc.Read(DataType.DataBlock, 99, 280, VarType.Bit, 1, 2))
                    {
                        PLC_Link[1].plc.WriteBit(DataType.DataBlock, 99, 146, 0, 1);    //扫码OK置1
                    }
                }
                if (temptype > 0)
                {
                    if (!EMArray[temptype - 1].Equals("0") && tempEM1ok == false)
                    {

                        if (indata.Contains(EMArray[temptype - 1]))
                        {
                            label20.Text = indata;
                            label20.BackColor = System.Drawing.Color.Green;
                            //PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 146, 0, 1);
                            tempEM1ok = true;

                        }
                        //else
                        //{
                        //    label20.BackColor = System.Drawing.Color.Red;
                        //    //PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 146, 1, 1);
                        //}

                    }
                    else
                    {
                        tempEM1ok = true;
                    }

                    if (!EMArray1[temptype - 1].Equals("0") && tempEM2ok == false)
                    {

                        if (indata.Contains(EMArray1[temptype - 1]) && (label20.Text != indata))
                        {
                            label29.Text = indata;
                            label29.BackColor = System.Drawing.Color.Green;
                            //PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 146, 0, 1);
                            tempEM2ok = true;
                        }
                        //else
                        //{
                        //    label29.BackColor = System.Drawing.Color.Red;
                        //    //PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 146, 1, 1);
                        //}
                    }
                    else
                    {
                        tempEM2ok = true;
                    }

                    if (!EMArray2[temptype - 1].Equals("0") && tempEM3ok == false)
                    {

                        if (indata.Contains(EMArray2[temptype - 1]) && (label20.Text != indata) && (label29.Text != indata))
                        {
                            label31.Text = indata;
                            label31.BackColor = System.Drawing.Color.Green;
                            //PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 146, 0, 1);
                            tempEM3ok = true;
                        }
                        //else
                        //{
                        //    label31.BackColor = System.Drawing.Color.Red;
                        //    //PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 146, 1, 1);
                        //}
                    }
                    else
                    {
                        tempEM3ok = true;
                    }

                    if (!EMArray3[temptype - 1].Equals("0") && tempEM4ok == false)
                    {

                        if (indata.Contains(EMArray3[temptype - 1]) && (label20.Text != indata) && (label29.Text != indata) && (label31.Text != indata))
                        {
                            label33.Text = indata;
                            label33.BackColor = System.Drawing.Color.Green;

                            tempEM4ok = true;
                        }
                        //else
                        //{
                        //    label33.BackColor = System.Drawing.Color.Red;
                        //    //PLC_Link[0].plc.WriteBit(DataType.DataBlock, 99, 146, 1, 1);
                        //}
                    }
                    else
                    {
                        tempEM4ok = true;
                    }
                }
                else
                {
                    MessageBox.Show("当前托盘型号为0");
                }
                //判定是否所有扫码都ok
                if (tempEM1ok && tempEM2ok && tempEM3ok && tempEM4ok && label37.Text != "")
                {
                    PLC_Link[1].plc.WriteBit(DataType.DataBlock, 99, 146, 0, 1);    //给出扫码OK信号
                }

            }
            catch (Exception exc)
            {
                MessageBox.Show(exc + "接收失败");
            }

        }
        public string byteToHexStr(byte[] bytes, int len)  //数组转十六进制字符
        {
            string returnStr = "";
            if (bytes != null)
            {
                for (int i = 0; i < len; i++)
                {
                    returnStr += bytes[i].ToString("X2");
                }
            }
            return returnStr;
        }
        private static byte[] strToToHexByte(string hexString) //字符串转16进制
        {
            //hexString = hexString.Replace(" ", " "); 
            if ((hexString.Length % 2) != 0)
                hexString = "0" + hexString;
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
        //计数清零
        private void button2_MouseDown(object sender, MouseEventArgs e)
        {
            PLC_Link[1].plc.WriteBit(DataType.DataBlock, 99, 146, 3, 1);
        }

        private void button2_MouseUp(object sender, MouseEventArgs e)
        {
            PLC_Link[1].plc.WriteBit(DataType.DataBlock, 99, 146, 3, 0);
        }
        bool gunConnect;
        bool autotype;
        //状态
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (comboBox3.Text.Contains("百度"))
            {
                label38.Text = "上线码";
            }
            //try
            //{
            if (!autotype)
            {
                int c;
                //PLC_Link[1].plc.Write(DataType.DataBlock, 99, 2, Convert.ToByte(comboBox3.SelectedIndex + 1));
                //c = Convert.ToInt32(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 283, VarType.Byte, 1)) - 1;
                 c = Convert.ToInt32(_plcStruct.byte_2) - 1;
                comboBox3.SelectedIndex = c;   //首次启动自动选择PLC现在被下发到型号。
                autotype = true;
            }
            //}
            //catch
            //{
            //    throw;
            //}
            //if (tempawrite==false)
            //{
            //    lab.Add(FormMain.FM10.useTable1);
            //    lab.Add(FormMain.FM10.useTable2);
            //    lab.Add(FormMain.FM10.useTable3);
            //    lab.Add(FormMain.FM10.useTable4);
            //    lab.Add(FormMain.FM10.useTable5);
            //    lab.Add(FormMain.FM10.useTable6);
            //    lab.Add(FormMain.FM10.useTable7);
            //    lab.Add(FormMain.FM10.useTable8);
            //    lab.Add(FormMain.FM10.useTable9);
            //    lab.Add(FormMain.FM10.useTable10);
            //    tempawrite = true;
            //}
            if (PLC_Link[1].readBoolen("DB1050.DBX24.1"))    //手动模式
            {
                button11.BackColor = Color.Green;
            }
            else
            {
                button11.BackColor = Color.FromArgb(128, 255, 255);
            }
            if (PLC_Link[1].readBoolen("DB1050.DBX24.0"))    //自动模式
            {
                button12.BackColor = Color.Green;
            }
            else
            {
                button12.BackColor = Color.FromArgb(128, 255, 255);
            }
            if (PLC_Link[1].readBoolen("DB1050.DBX1.6"))    //空托盘
            {
                button15.BackColor = Color.Green;
            }
            else
            {
                button15.BackColor = Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
            }
            //if (PLC_Link[0].readBoolen("DB1050.DBX1.4"))    //返修上线
            //{
            //    button14.BackColor = Color.Green;
            //}
            //else
            //{
            //    button14.BackColor = Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
            //}
            //if (PLC_Link[0].readBoolen("DB1050.DBX1.3"))    //测试上线
            //{
            //    button16.BackColor = Color.Green;
            //}
            //else
            //{
            //    button16.BackColor = Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))));
            //}
            //PLC点位报警，未验证。
            //报警
            try
            {
                if (PLC_Link[1].ReadByte(DataType.DataBlock, 1080, 2) > 0)
                {
                    alarmNum = File.ReadAllLines(Application.StartupPath + "\\报警配置.txt", Encoding.UTF8);
                    for (int i = 0; i < 8; i++)
                    {
                        if (PLC_Link[1].readBoolen("DB1080.DBX2." + i.ToString()))
                        {
                            //inAlarm("OA报警[1]夹紧气缸前进超时A"); 
                            label242.Text = alarmNum[i];
                            clear = true;
                            break;
                        }
                    }
                }
                else if (PLC_Link[0].ReadByte(DataType.DataBlock, 1080, 3) > 0)
                {
                    alarmNum = File.ReadAllLines(Application.StartupPath + "\\报警配置.txt", Encoding.UTF8);
                    for (int i = 0; i < 8; i++)
                    {
                        if (PLC_Link[0].readBoolen("DB1080.DBX3." + i.ToString()))
                        {
                            //inAlarm("OA报警[1]夹紧气缸前进超时A"); 
                            label242.Text = alarmNum[i + 8];
                            break;
                        }
                    }
                }
                else
                {
                    if (clear)
                    {
                        label242.Text = "";
                        clear = false;
                    }
                }
            }
            catch 
            {
                
            }
        }

                static string GetLatestFileNameInfo(string dir, string ext)
        {
            DirectoryInfo d = new DirectoryInfo(dir);
            DateTime temp = new DateTime();
            string FileName = "0";
            foreach (FileInfo file in d.GetFiles())
            {
                if (file.Extension.ToUpper() == ext.ToUpper())
                {
                    if (file.CreationTime > temp)
                    {
                        temp = file.CreationTime;
                        FileName = file.FullName;
                    }
                }
            }

            return FileName;
        }

        //delete photo
        static string deletePhtor(string dir, string ext)
        {
            DirectoryInfo d = new DirectoryInfo(dir);
            string FileName = "0";

            foreach (FileInfo file in d.GetFiles())
            {
                //if (file.Extension.ToUpper() == ext.ToUpper())
                //{
                try
                {
                    File.Delete(file.FullName);
                }
                catch
                { }
                //}
            }

            return FileName;
        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //if ()
                //{
                //计划生产数
                //PLC_Link[0].plc.Write(DataType.DataBlock, 99, 6, Convert.ToInt16(textBox1.Text));

                //将参数下发PLC
                string sql = "select [saveDate], [typeName], [产品系列号], [OP10螺钉数1], [OP10螺钉数2], [OP10节拍], [OP20螺钉数1], [OP20螺钉数2], [OP20节拍], [OP30螺钉数1], [OP30螺钉数2], [OP30节拍], [OP40螺钉数1], [OP40螺钉数2], [OP40节拍], [OP50螺钉数1], [OP50螺钉数2], [OP50节拍], [OP60螺钉数1], [OP60螺钉数2], [OP60节拍], [OP70螺钉数1], [OP70螺钉数2], [OP70节拍], [OP80螺钉数1], [OP80螺钉数2], [OP80节拍], [OP90正压程序号], [OP90负压程序号], [OP90节拍], [OP110节拍], [OP130节拍] from parameterSetting where typeName = '{0}'";
                sql = string.Format(sql, comboBox3.Text);
                SqlDataReader objReader = SQLHelp.GetReader(sql);
                while (objReader.Read())
                {
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 1, Convert.ToByte(Convert.ToInt32(objReader["产品系列号"]) + 1));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 17, Convert.ToByte(Convert.ToInt32(objReader["OP10螺钉数1"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 18, Convert.ToByte(Convert.ToInt32(objReader["OP10螺钉数2"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 147, Convert.ToByte(Convert.ToInt32(objReader["OP10节拍"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 27, Convert.ToByte(Convert.ToInt32(objReader["OP20螺钉数1"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 28, Convert.ToByte(Convert.ToInt32(objReader["OP20螺钉数2"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 161, Convert.ToByte(Convert.ToInt32(objReader["OP20节拍"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 171, Convert.ToByte(Convert.ToInt32(objReader["OP30节拍"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 47, Convert.ToByte(Convert.ToInt32(objReader["OP40螺钉数1"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 48, Convert.ToByte(Convert.ToInt32(objReader["OP40螺钉数2"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 181, Convert.ToByte(Convert.ToInt32(objReader["OP40节拍"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 57, Convert.ToByte(Convert.ToInt32(objReader["OP50螺钉数1"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 58, Convert.ToByte(Convert.ToInt32(objReader["OP50螺钉数2"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 191, Convert.ToByte(Convert.ToInt32(objReader["OP50节拍"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 67, Convert.ToByte(Convert.ToInt32(objReader["OP60螺钉数1"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 68, Convert.ToByte(Convert.ToInt32(objReader["OP60螺钉数2"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 201, Convert.ToByte(Convert.ToInt32(objReader["OP60节拍"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 77, Convert.ToByte(Convert.ToInt32(objReader["OP70螺钉数1"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 78, Convert.ToByte(Convert.ToInt32(objReader["OP70螺钉数2"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 211, Convert.ToByte(Convert.ToInt32(objReader["OP70节拍"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 87, Convert.ToByte(Convert.ToInt32(objReader["OP80螺钉数1"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 88, Convert.ToByte(Convert.ToInt32(objReader["OP80螺钉数2"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 221, Convert.ToByte(Convert.ToInt32(objReader["OP80节拍"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 231, Convert.ToByte(Convert.ToInt32(objReader["OP90节拍"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 241, Convert.ToByte(Convert.ToInt32(objReader["OP110节拍"])));
                    PLC_Link[1].plc.Write(DataType.DataBlock, 99, 261, Convert.ToByte(Convert.ToInt32(objReader["OP130节拍"])));
                }
                objReader.Close();
                //产品型号
                PLC_Link[1].plc.Write(DataType.DataBlock, 99, 2, Convert.ToByte(comboBox3.SelectedIndex + 1));
                label28.Text = "换型成功！";
                //}
                //else
                //{
                //    MessageBox.Show("非法输入,请输入大于0的值！");
                //}

            }
            catch (Exception a)
            {
                MessageBox.Show("换型操作失败！" + a.ToString());
            }
            try
            {
                //string sql = "select [产品系列号] from parameterSetting where typeName = '{0}'";
                string sql = "select [row] from parameterSetting where typeName = '{0}'";
                sql = string.Format(sql, comboBox3.Text);
                SqlDataReader objReader = SQLHelp.GetReader(sql);
                while (objReader.Read())
                {
                    //typeNameTemp = Convert.ToInt32(objReader["产品系列号"]) + 1;
                    typeNameTemp = Convert.ToInt32(objReader["row"]);
                    model = typeNameTemp;
                }
                objReader.Close();

                pictureBox3.Image = Image.FromFile(Application.StartupPath + @"\SOP\" + typeNameTemp + ".png");
            }
            catch (Exception)
            {

                //throw;
            }
        }
        //call the monitor
        int secondCount;
        int secondCount1;
        System.Timers.Timer timer = new System.Timers.Timer();
        System.Timers.Timer timercall = new System.Timers.Timer();
        private void button7_Click(object sender, EventArgs e)
        {
            PLC_Link[1].plc.WriteBit(DataType.DataBlock, 99, 616, 0, !Convert.ToBoolean(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 616, VarType.Bit, 1, 0)));
            if (Convert.ToBoolean(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 616, VarType.Bit, 1, 0)))
            {
                timer.Start();
                secondCount = 0;
            }
            if (Convert.ToBoolean(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 616, VarType.Bit, 1, 0)) == false)
            {
                timer.Stop();

                string sql = "insert into calRecord([callStation],[callOP],[callOptions],[callTimers],[callDateTime]) values('{0}','{1}','{2}','{3}','{4}')";
                sql = string.Format(sql, "OP10", proData.operatorter, "呼叫班长", secondCount, DateTime.Now.ToString());
                num1 = SQLHelp.AddData(sql);
            }

        }
        //呼叫物料
        private void button8_Click(object sender, EventArgs e)
        {
            PLC_Link[1].plc.WriteBit(DataType.DataBlock, 99, 616, 1, !Convert.ToBoolean(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 616, VarType.Bit, 1, 1)));

            if (Convert.ToBoolean(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 616, VarType.Bit, 1, 1)))
            {
                timercall.Start();
                secondCount1 = 0;
            }
            if (Convert.ToBoolean(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 616, VarType.Bit, 1, 1)) == false)
            {
                timercall.Stop();

                string sql = "insert into calRecord([callStation],[callOP],[callOptions],[callTimers],[callDateTime]) values('{0}','{1}','{2}','{3}','{4}')";
                sql = string.Format(sql, "OP10", proData.operatorter, "呼叫物料", secondCount1, DateTime.Now.ToString());
                num1 = SQLHelp.AddData(sql);
            }
        }
        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            secondCount++;
            timer.Start();
        }
        void timercall_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            secondCount1++;
            timercall.Start();
        }

        ////查看打钉
        ////List<Label> lab = new List<Label>();
        private void button6_Click(object sender, EventArgs e)
        {
            //dading();
        }
        //查看拍照
        System.Timers.Timer timerPhoto = new System.Timers.Timer();
        private void button5_Click(object sender, EventArgs e)
        {
            //timerPhoto.Enabled = true;
            //timerPhoto.Interval = 1000;
            //timerPhoto.AutoReset = false;
            //timerPhoto.Elapsed += new System.Timers.ElapsedEventHandler(timerPhoto_Elapsed);
            //List<Label> lab = new List<Label> { useTable1, useTable2, useTable3, useTable4, useTable5, useTable6, useTable7, useTable8, useTable9, useTable10, useTable11, useTable12, useTable13, useTable14, useTable15, useTable16, useTable17, useTable18, useTable19 };
            //for (int i = 0; i < 19; i++)
            //{
            //    lab[i].Visible = false;
            //}
            //timerPhoto.Start();
        }
        void timerPhoto_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!Convert.ToBoolean(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 280, VarType.Bit, 1, 1)))
            {
                //显示拍照照片
                string file = GetLatestFileNameInfo(@"d:\\1", ".jpeg");
                if (file != "" && file != null && !file.Equals("0"))
                {
                    try
                    {
                        label28.Text = "照片名为" + file;
                        //pictureBox3.Image = Image.FromFile(file);
                        FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
                        int byteLength = (int)fs.Length;
                        byte[] fileBytes = new byte[byteLength];
                        fs.Read(fileBytes, 0, byteLength);
                        fs.Close();
                        pictureBox3.Image = Image.FromStream(new MemoryStream(fileBytes));
                    }
                    catch
                    {
                        //this.WindowState = FormWindowState.Minimized;
                        //MessageBox.Show("拍照图片显示错误");
                    }
                }
                else
                {

                }
                GC.Collect();
                timerPhoto.Start();
            }
        }

        #region Drag and drop event
        private Point m_lastPoint;
        private Point m_lastMPoint;
        //1
        private void useTable1_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable1.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //2
        private void useTable2_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable2_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable2.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //3
        private void useTable3_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable3_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable3.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //4
        private void useTable4_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable4_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable4.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //5
        private void useTable5_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable5_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable5.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //6
        private void useTable6_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable6_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable6.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //7
        private void useTable7_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable7_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable7.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //8
        private void useTable8_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable8_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable8.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //9
        private void useTable9_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable9_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable9.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //10
        private void useTable10_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable10_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable10.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //11
        private void useTable11_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable11_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable11.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //12
        private void useTable12_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable12_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable12.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //13
        private void useTable13_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable13_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable13.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //14
        private void useTable14_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable14_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable14.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //15
        private void useTable15_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable15_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable15.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //16
        private void useTable16_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable16_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable16.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //17
        private void useTable17_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable17_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable17.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //18
        private void useTable18_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable18_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable18.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        //19
        private void useTable19_MouseDown(object sender, MouseEventArgs e)
        {
            m_lastMPoint = Control.MousePosition;
            m_lastPoint = (sender as Label).Location;
        }
        private void useTable19_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                useTable19.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
            }
        }
        #endregion

        //save location
        private void button10_Click(object sender, EventArgs e)
        {
            List<Label> lab = new List<Label> { useTable1, useTable2, useTable3, useTable4, useTable5, useTable6, useTable7, useTable8, useTable9, useTable10, useTable11, useTable12, useTable13, useTable14, useTable15, useTable16, useTable17, useTable18, useTable19 };
            LableLocations lableLocations = new LableLocations();
            Locations locations = new Locations();
            for (int i = 0; i < lab.Count; i++)
            {
                locations.xlocation[i] = lab[i].Location.X;
                locations.ylocation[i] = lab[i].Location.Y;
            }
            lableLocations.type = 1;
            lableLocations.datas = locations;
            string strfile = JsonConvert.SerializeObject(lableLocations);
            switch (typeNameTemp)
            {
                case 1:
                    File.WriteAllText(Application.StartupPath + "\\ctrloPoint1.txt", strfile);
                    break;
                case 2:
                    File.WriteAllText(Application.StartupPath + "\\ctrloPoint2.txt", strfile);
                    break;
                case 3:
                    File.WriteAllText(Application.StartupPath + "\\ctrloPoint3.txt", strfile);
                    break;
                case 4:
                    File.WriteAllText(Application.StartupPath + "\\ctrloPoint4.txt", strfile);
                    break;
            }
        }
        #region Gun发送指令函数
        public void GunSend(string str)
        {
            try
            {
                byte[] buffer = new byte[64];
                string[] strTemp = str.Split();
                for (int i = 0; i < strTemp.Length; i++)
                {
                    buffer[i] = Byte.Parse(strTemp[i], System.Globalization.NumberStyles.AllowHexSpecifier);
                }
                socketSendGun.Send(buffer);
            }
            catch
            {

            }
        }
        #endregion
        #region 将16进制的字符串形式转换为对应的ascii码
        public string stringHextoASCII(string s)
        {
            byte[] buff = new byte[s.Length / 2];
            int index = 0;
            for (int i = 0; i < s.Length; i += 2)
            {
                buff[index] = Convert.ToByte(s.Substring(i, 2), 16);
                ++index;
            }
            string result = Encoding.Default.GetString(buff);
            return result;
        }
        #endregion

        void gunConnectStart()
        {
            while (gunConnect == false)
            {
                try
                {
                    //创建负责通信的Socket
                    socketSendGun = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    IPAddress ip = IPAddress.Parse("192.168.1.17");
                    IPEndPoint point = new IPEndPoint(ip, 4545);
                    IAsyncResult connResult = socketSendGun.BeginConnect(ip, 4545, null, null);
                    //WaitHandle.WaitOne 方法阻止当前线程,直到当前的 WaitHandle 收到信号
                    connResult.AsyncWaitHandle.WaitOne(2000, true);  //等待2秒

                    if (!connResult.IsCompleted)
                    {
                        socketSendGun.Close();
                        //MessageBox.Show("螺钉枪连接失败");
                    }
                    else
                    {
                        GunSend("30 30 32 30 30 30 30 31 30 30 36 30 30 30 30 30 30 30 30 30 00");
                        GunSend("30 30 36 30 30 30 30 38 30 30 31 30 30 30 30 30 30 30 30 30 31 32 30 31 30 30 31 33 31 31 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 00");
                        gunConnect = true;
                        //MessageBox.Show("连接成功");
                        Thread thGun = new Thread(ReciveGan);
                        thGun.IsBackground = true;
                        thGun.Start();
                    }

                }
                catch
                {
                    MessageBox.Show("螺钉枪连接失败");
                }
                Thread.Sleep(10);
            }
        }
        int typeNameTemp = 0;
        private byte temptype;
        private object tmpid;
        private byte tmptyp;
        private string[] stepNum = new string[20];
        private int num2;

        void dading()
        {

            for (int i = 0; i < 5; i++)
            {
                timerPhoto.Stop();
                timerPhoto.Enabled = false;
                Thread.Sleep(10);
            }
            label28.Text = "型号为" + _plcStruct.byte_2.ToString();
            if (_plcStruct.byte_2 > 0 && _plcStruct.byte_2 < 150)
            {

                string sql = "select [产品系列号] from parameterSetting where typeName = '{0}'";
                sql = string.Format(sql, label2.Text);
                SqlDataReader objReader = SQLHelp.GetReader(sql);
                while (objReader.Read())
                {
                    typeNameTemp = Convert.ToInt32(objReader["产品系列号"]) + 1;

                }
                objReader.Close();
                switch (typeNameTemp)
                {
                    case 1:
                        try
                        {
                            //pictureBox3.Image = Image.FromFile(Application.StartupPath + @"\打钉照片\GEMINI\分配箱.png");
                            string st = Application.StartupPath + @"\打钉照片\GEMINI\分配箱.png";
                            FileStream fs = new FileStream(st, FileMode.Open, FileAccess.Read);
                            int byteLength = (int)fs.Length;
                            byte[] fileBytes = new byte[byteLength];
                            fs.Read(fileBytes, 0, byteLength);
                            fs.Close();
                            pictureBox3.Image = Image.FromStream(new MemoryStream(fileBytes));
                        }
                        catch
                        {
                            MessageBox.Show("图片打开错误,请检查是否存在图片-分配箱.png");

                        }
                        break;
                    case 2:
                        try
                        {
                            //pictureBox3.Image = Image.FromFile(@"打钉照片\GEMINI\蒸发箱.png");
                            FileStream fs = new FileStream(@"打钉照片\GEMINI\蒸发箱.png", FileMode.Open, FileAccess.Read);
                            int byteLength = (int)fs.Length;
                            byte[] fileBytes = new byte[byteLength];
                            fs.Read(fileBytes, 0, byteLength);
                            fs.Close();
                            pictureBox3.Image = Image.FromStream(new MemoryStream(fileBytes));
                        }
                        catch
                        {
                            MessageBox.Show("图片打开错误,请检查是否存在图片-蒸发箱.png");
                        }
                        break;
                    case 3:
                        try
                        {
                            //pictureBox3.Image = Image.FromFile(@"打钉照片\ESX\前空调.png");
                            FileStream fs = new FileStream(@"打钉照片\ESX\前空调.png", FileMode.Open, FileAccess.Read);
                            int byteLength = (int)fs.Length;
                            byte[] fileBytes = new byte[byteLength];
                            fs.Read(fileBytes, 0, byteLength);
                            fs.Close();
                            pictureBox3.Image = Image.FromStream(new MemoryStream(fileBytes));
                        }
                        catch
                        {
                            MessageBox.Show("图片打开错误,请检查是否存在图片-前空调.png");
                        }
                        break;
                    case 4:
                        try
                        {
                            //pictureBox3.Image = Image.FromFile(@"打钉照片\ESX\后空调.png");
                            FileStream fs = new FileStream(@"打钉照片\ESX\后空调.png", FileMode.Open, FileAccess.Read);
                            int byteLength = (int)fs.Length;
                            byte[] fileBytes = new byte[byteLength];
                            fs.Read(fileBytes, 0, byteLength);
                            fs.Close();
                            pictureBox3.Image = Image.FromStream(new MemoryStream(fileBytes));
                        }
                        catch
                        {
                            MessageBox.Show("图片打开错误,请检查是否存在图片-后空调.png");
                        }
                        break;
                }

                GC.Collect();
                #region initialize screw display  
                if (Convert.ToInt16(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 17, VarType.Byte, 1)) + Convert.ToInt16(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 18, VarType.Byte, 1)) > 0)
                {
                    List<Label> lab = new List<Label> { FormMain.FM10.useTable1, useTable2, useTable3, useTable4, useTable5, useTable6, useTable7, useTable8, useTable9, useTable10, useTable11, useTable12, useTable13, useTable14, useTable15, useTable16, useTable17, useTable18, useTable19 };
                    LableLocations lableLocations = new LableLocations();
                    string filecode = File.ReadAllText(Application.StartupPath + @"\ctrloPoint" + typeNameTemp + ".txt");
                    try
                    {
                        lableLocations = JsonConvert.DeserializeObject<LableLocations>(filecode);
                        if (lableLocations != null)
                        {
                            for (int i = 0; i < Convert.ToInt16(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 17, VarType.Byte, 1)) + Convert.ToInt16(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 18, VarType.Byte, 1)); i++)
                            {
                                lab[i].Location = new System.Drawing.Point(lableLocations.datas.xlocation[i], lableLocations.datas.ylocation[i]);
                                lab[i].Visible = true;
                                //FormMain.FM10.useTable10.Visible = false;
                            }
                            for (int i = Convert.ToInt16(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 17, VarType.Byte, 1)) + Convert.ToInt16(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 18, VarType.Byte, 1)); i < 19; i++)
                            {
                                lab[i].Visible = false;
                            }
                        }
                        else
                        {
                            MessageBox.Show("数据为空");
                        }
                    }
                    catch
                    {
                        MessageBox.Show("数据读取出现错误");
                    }
                    #endregion 
                }
                else
                {
                    List<Label> lab = new List<Label> { FormMain.FM10.useTable1, useTable2, useTable3, useTable4, useTable5, useTable6, useTable7, useTable8, useTable9, useTable10, useTable11, useTable12, useTable13, useTable14, useTable15, useTable16, useTable17, useTable18, useTable19 };
                    for (int i = Convert.ToInt16(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 17, VarType.Byte, 1)) + Convert.ToInt16(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 18, VarType.Byte, 1)); i < 19; i++)
                    {
                        lab[i].Visible = false;
                    }
                }
            }
        }

        private void button10_MouseDown(object sender, MouseEventArgs e)
        {
            button10.BackColor = Color.Green;
        }
        public static void CopyAllFile(string sources, string dest)
        {
            if (!Directory.Exists(dest))
            {
                Directory.CreateDirectory(dest);
            }

            string[] files = Directory.GetFileSystemEntries(sources);
            foreach (var file in files)
            {
                string destFileName = Path.Combine(dest, Path.GetFileName(file));
                if (File.Exists(file))
                {
                    File.Copy(file, destFileName, true);
                }
                else
                {
                    if (!Directory.Exists(file))
                    {
                        Directory.CreateDirectory(file);
                    }
                    else
                    {
                        CopyAllFile(Path.Combine(sources, Path.GetFileName(file)), destFileName);
                    }
                }
            }
        }
        //设定权限模板
        //private void button6_Click(object sender, EventArgs e) //保存按钮
        //{
        //    Program.PernChk(Program.userlogin);
        //    if (Program.userlogin.UserID == 2 || Program.userlogin.UserID == 1)
        //    {
        //        Save = true;
        //    }
        //    else
        //    {
        //        MessageBox.Show("没有操作权限", "提示！");
        //        return;
        //    }

        //}
        //手动模式按钮
        private void button11_MouseDown(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[1].WriteBoolen("DB1050.DBX0.1", true);
        }
        private void button11_MouseUp(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[1].WriteBoolen("DB1050.DBX0.1", false);
            if ((Program.userlogin.UserID == 1) || (Program.userlogin.UserID == 2))      //登录账户有操作权限
            {
                OpenForm(new FormManMode());
            }
            else    //进行登录操作
            {
                MessageBox.Show("没有操作权限", "提示！");
                return;
            }
        }
        //自动模式按钮
        private void button12_MouseDown(object sender, MouseEventArgs e) 
        {
            FormMain.PLC_Link[1].WriteBoolen("DB1050.DBX0.0", true);
        }
        private void button12_MouseUp(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[1].WriteBoolen("DB1050.DBX0.0", false);
            CloseForm();
        }
        //报警复位按钮
        private void button13_MouseDown(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[1].WriteBoolen("DB1050.DBX1.2", true);
        }

        private void button13_MouseUp(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[1].WriteBoolen("DB1050.DBX1.2", false);
        }
        //返回原位（大复位按钮）
        private void button6_MouseDown(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[1].WriteBoolen("DB1050.DBX1.1", true);
        }
        private void button6_MouseUp(object sender, MouseEventArgs e)
        {
            FormMain.PLC_Link[1].WriteBoolen("DB1050.DBX1.1", false);
        }
        //返修上线
        private void button14_Click(object sender, EventArgs e)
        {
            PLC_Link[1].WriteBoolen("DB1050.DBX1.4", !PLC_Link[1].readBoolen("DB1050.DBX1.4"));
        }
        //空托盘
        private void button15_Click(object sender, EventArgs e)
        {
            PLC_Link[1].WriteBoolen("DB1050.DBX1.6", !PLC_Link[1].readBoolen("DB1050.DBX1.6"));
        }
        //测试上线按钮
        private void button16_Click(object sender, EventArgs e)
        {
            PLC_Link[1].WriteBoolen("DB1050.DBX1.3", !PLC_Link[1].readBoolen("DB1050.DBX1.3"));
        }

        private void label2_TextChanged(object sender, EventArgs e)
        {
            int c;
            //PLC_Link[1].plc.Write(DataType.DataBlock, 99, 2, Convert.ToByte(comboBox3.SelectedIndex + 1));
            //c = Convert.ToInt32(PLC_Link[1].plc.Read(DataType.DataBlock, 99, 283, VarType.Byte, 1)) - 1;
            c = Convert.ToInt32(_plcStruct.byte_2) - 1;
            comboBox3.SelectedIndex = c;
        }

        //强制不合格按钮
        private void button17_MouseDown(object sender, MouseEventArgs e)
        {
            PLC_Link[1].WriteBoolen("DB1050.DBX1.5", true);
        }

        private void button17_MouseUp(object sender, MouseEventArgs e)
        {
            PLC_Link[1].WriteBoolen("DB1050.DBX1.5", false);
        }
    }
}
